package com.weiaibenpao.demo.chislim.sport;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.RunningUtils;
import com.weiaibenpao.demo.chislim.bean.AddSportsBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.sport.bean.RegionDataBean;
import com.weiaibenpao.demo.chislim.sport.utils.PolyLines;
import com.weiaibenpao.demo.chislim.ui.BaseRunningActivity;
import com.weiaibenpao.demo.chislim.ui.MusicTypeActivity;
import com.weiaibenpao.demo.chislim.util.LatLong_impl;
import com.weiaibenpao.demo.chislim.util.SlideUnlockView;
import com.weiaibenpao.demo.chislim.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.util.VoicePlayerUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.weiaibenpao.demo.chislim.RunningService.CALORIE;
import static com.weiaibenpao.demo.chislim.RunningService.DISTANCE;
import static com.weiaibenpao.demo.chislim.RunningService.FINISH;
import static com.weiaibenpao.demo.chislim.RunningService.PACE;
import static com.weiaibenpao.demo.chislim.RunningService.PAUSE;
import static com.weiaibenpao.demo.chislim.RunningService.RUNNING;
import static com.weiaibenpao.demo.chislim.RunningService.STEP;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.BEAN;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.SELECT_NAME;
import static com.weiaibenpao.demo.chislim.sport.utils.PolyLines.POLYLINE_OVER_SUCCESS;

public class SportOutDistrictActivity extends BaseRunningActivity implements RunningService.OnDataUpdatedListener {

    @BindView(R.id.mapView)
    MapView mapView;
    Context context;

    AMap aMap;

    @BindView(R.id.switch_layout)
    View switchLayout;
    @BindView(R.id.dis)
    TextView dis;
    @BindView(R.id.sportTime)
    TextView sportTime;
    @BindView(R.id.tv_steps)
    TextView tvSteps;
    @BindView(R.id.mySpeed)
    TextView mySpeed;
    @BindView(R.id.myCalories)
    TextView myCalories;
    @BindView(R.id.start)
    ImageView start;
    @BindView(R.id.lock)
    ImageView lock;

    @BindView(R.id.stop)
    TextView stop;
    @BindView(R.id.countdown_view)
    TextView countdownText;
    @BindView(R.id.showView)
    LinearLayout showView;
    @BindView(R.id.music_tv)
    TextView music_tv;
    @BindView(R.id.slideUnlockView)
    SlideUnlockView slideUnlockView;
    @BindView(R.id.mask)
    View mask;
    @BindView(R.id.location_tv)
    TextView location_tv;

    float disOld;               //运动记录
    /**
     * 1 正在跑步
     * 2  没有点开始
     */
    private int runStatu = 2;

    LatLong_impl latLong_impl;
    RunningService mService;
    private VoicePlayerUtil voicePlayerUtil;
    private SharedPreferences mSharedPreferences;
    String disData = "0.00";                //当前运动距离 单位是千米
    String current_time;
    double districtDistance = 0;         //行政区周长


    DecimalFormat decimalFormat = new DecimalFormat("0.00");

    WindowManager wm;
    int widthScreen;                  //获取手屏幕跨度
    int heightScreen;


    private PolylineOptions polylineOption;
    private PolylineOptions polylineOption2;
    int num; //总点数
    private RegionDataBean dataBean;
    private boolean isFirstRun = true;//是开启跑步
    private boolean isFirstUpData = true;//是否第一次更新跑步
    private PolyLines polylines;
    private String selectName;
    private RunningPreferences preferences;
    private String distract_code;
    private int countOld;
    private boolean isStartPointDrawn;
    private final int NUM_SUCCESS = 101000;
    private int id;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case POLYLINE_OVER_SUCCESS:
                    polylineOption = (PolylineOptions) msg.obj;
                    num = polylineOption.getPoints().size();
                    if (polylineOption != null && polylineOption.getPoints().size() != 0) {
                        if (!isStartPointDrawn) {
                            setMarkView(polylineOption.getPoints().get(0));

                        }
                        if (disOld != 0) {
                            polylineOption2.width(12).color(Color.parseColor("#cc358f"));
                            drawLine(disOld);

                        }

                    }
                    break;
                case NUM_SUCCESS:
                    aMap.addPolyline(polylineOption2);

                    if (getTotalDistance() != 0 && isFirstUpData) {
                        isFirstUpData = false;
                        polylineOption2.width(12).color(Color.parseColor("#7a2075"));
                        drawLine(getTotalDistance() + disOld);
                        Log.e("wlx", "handleMessage:第一是否进来 ");
                    }
                    break;
            }
        }
    };
    private String city;
    private String area;
    private String province;
    private long totalTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_running);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
        dataBean = ((RegionDataBean) getIntent().getSerializableExtra(BEAN));
        initIntent();
        mapView.onCreate(savedInstanceState);         // 此方法必须重写
        context = new WeakReference<Activity>(this).get();
//        voicePlayerUtil = new VoicePlayerUtil(SportOutDistrictActivity.this);
        latLong_impl = new LatLong_impl(context);
        current_time = latLong_impl.getDate();
        preferences = RunningPreferences.getInstance();
        int state = preferences.getRunningState();
        if (state == RunningService.RUNNING || state == RunningService.PAUSE) {
            lock.setVisibility(View.VISIBLE);
            stop.setVisibility(View.VISIBLE);
            start.setImageResource(R.drawable.ic_finish);
            if (state == RunningService.PAUSE) {
                stop.setText("继续");
            }
            restoreDataDisplay();//由于服务端的回调有过滤，例如如果精度不满足，就不回调，所以这里进行一次手动恢复现场
        }
        initMap();
        initLock();


    }


    @Override
    public void checkPerMissions() {
        super.checkPerMissions();
    }

    private void initLock() {
        slideUnlockView.setOnUnLockListener(new SlideUnlockView.OnUnLockListener() {
            @Override
            public void setUnLocked(boolean lock) {
                if (lock) {
                    mask.setVisibility(View.GONE);
                    slideUnlockView.reset();
                    switchLayout.setVisibility(View.VISIBLE);
                    slideUnlockView.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initIntent() {
        if (dataBean != null) {
            selectName = getIntent().getStringExtra(SELECT_NAME);
            distract_code = dataBean.getCode();
            disOld =  Float.parseFloat(decimalFormat.format(dataBean.getTotalDistance() * 1000));
            totalTime = dataBean.getTotalTime();
            id = dataBean.getId();
            districtDistance = Float.parseFloat(decimalFormat.format(dataBean.getYudingDistance() * 1000));
            province = dataBean.getProvince();
            city = dataBean.getCity();
            area = dataBean.getArea();


        }
    }

    public void transformDistrict(String time) {
        String[] array = time.split(",");
        for (int i = 0; i < array.length; i++) {
            if (i == 0) {
                province = array[i];
            } else if (i == 1) {
                city = array[1];
            } else {
                area = array[2];
            }
        }

    }

    /**
     * 跑步总里程
     *
     * @return 单位米
     */
    private float getTotalDistance() {
        return Float.parseFloat(disData)*1000 ;
    }

    private void restoreDataDisplay() {
        showAddToWhiteListNotice();
        //当前运动近距离
        mySpeed.setText(preferences.getRunningPace());
        tvSteps.setText(preferences.getRunningStep() + "");
        sportTime.setText(RunningUtils.getHmsTime(preferences.getRunningTime()));
        selectName = preferences.getDistrictSelect();
        disOld = Float.parseFloat(decimalFormat.format(preferences.getDistrictTotalDistance() * 1000)) ;
        distract_code = preferences.getDistrictCode();
        totalTime = preferences.getDistrictTotalTime();
        districtDistance = Float.parseFloat(decimalFormat.format(preferences.getDistrictDistance() * 1000));
        id = preferences.getDistrictID();
        String district = preferences.getDistrict();
        transformDistrict(district);
        disData = decimalFormat.format(preferences.getRunningDistance() / 1000);
        dis.setText(disData);
        mySpeed.setText(preferences.getRunningPace());
        tvSteps.setText(preferences.getRunningStep() + "");
        myCalories.setText(preferences.getRunningCalorie());

    }


    public static void openActivity(Context context, RegionDataBean regionBean, String selectName) {
        Intent intent = new Intent(context, SportOutDistrictActivity.class);
        intent.putExtra(BEAN, regionBean);
        intent.putExtra(SELECT_NAME, selectName);
        context.startActivity(intent);
    }

    /**
     * 实例化地图
     */
    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setTrafficEnabled(true);           // 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 地图模式
        drawLines();
        wm = this.getWindowManager();
        widthScreen = wm.getDefaultDisplay().getWidth();
        heightScreen = wm.getDefaultDisplay().getHeight();
        if (polylineOption2 == null) {
            polylineOption2 = new PolylineOptions();

        }
    }

    private void drawLines() {
        polylines = new PolyLines(this, aMap);
        polylines.drawLIne(distract_code, selectName, mHandler);
    }

    /**
     * 绘制轨迹
     */
    int runNum = 0;

    /**
     *
     * @param dis 运动总距离
     */
    public void drawLine(float dis) {//dis  单位米
        if (polylineOption2.getPoints()!=null){
            polylineOption2.getPoints().clear();
        }
        int h;
        if (dis >= districtDistance) {
            h=num-1;
            showOver();
        } else {
            h = (int) (num * (dis / districtDistance));
            if (h==num){
                h-=1;
            }
        }
        Log.e("wlx", "h: "+h+" runNum:" +runNum);
        for (int m = runNum; m <= h; m++) {
            polylineOption2.add(polylineOption.getPoints().get(m));
        }
        runNum = h;
        mHandler.sendEmptyMessage(NUM_SUCCESS);

    }

    private void setMarkView(LatLng latLng) {
        View view = View.inflate(context, R.layout.mark_layout, null);
        TextView sportMark = (TextView) view.findViewById(R.id.sportTitle);
        sportMark.setText("起");
        Bitmap bitmap = convertViewToBitmap(view);
        drawMarkerOnMap(latLng, bitmap, String.valueOf("起"));
        isStartPointDrawn = true;
    }

    private Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        return view.getDrawingCache();
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) {

        if (aMap != null && point != null) {

            return aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
        }
        return null;
    }

    /**
     * 跑步完成显示
     */
    private void showOver() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = LayoutInflater.from(this).inflate(R.layout.region_run_over, null);
        view.findViewById(R.id.close_run).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tv_city = (TextView) view.findViewById(R.id.tv_city);
        tv_city.setText(province + city + area);
        dialog.setView(view);
        dialog.show();

    }


    @OnClick({R.id.lock, R.id.stop, R.id.start, R.id.music_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lock:
                switchLayout.setVisibility(View.GONE);
                mask.setVisibility(View.VISIBLE);
                slideUnlockView.setVisibility(View.VISIBLE);
                break;
            case R.id.stop:
                if (mService != null) {
                    String pause = stop.getText().toString();
                    if (pause.equals("暂停")) {
                        stop.setText("继续");
//                        voicePlayerUtil.startVoice("跑步暂停");
                        SpeechUtil.getInstance().speak("暂停跑步");
                        mService.setState(PAUSE);
                    } else if (pause.equals("继续")) {
                        if(goEnableGPS()) return;
                        stop.setText("暂停");
//                        voicePlayerUtil.startVoice("跑步继续");
                        SpeechUtil.getInstance().speak("继续跑步");
                        mService.setState(RUNNING);
                    }
                }
                break;
            case R.id.start:             //倒计时后  开始 暂停 的按钮
                //考虑服务一直在，但是界面销毁然后重新进入时候的UI
                if (mService != null) {
                    if (mService.hasOngoingRunning()) {
//                        showDialog();
                        if (getTotalDistance()>= 100.0) {
                            showUploadDialog();
                        } else {
                            overDialog();
                        }

                    } else {
                        if(goEnableGPS()) return;
                        if (isFirstRun) {
                            isFirstRun = false;
                            startCountdown();

                        }
                    }
                }
                break;
            case R.id.music_tv:
                Intent intent = new Intent(this, MusicTypeActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void overDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("此次运动距离太短，无法保存记录");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {


            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                mService.setState(FINISH);
                finish();
            }
        });
        builder.show();
    }

    public void startCountdown() {
        countdownText.setVisibility(View.VISIBLE);
        runStatu = 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= -1; i--) {
                    try {
                        final int index = i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (index > 0) {
//                                    voicePlayerUtil.startVoice(String.valueOf(index));
                                    SpeechUtil.getInstance().speak(String.valueOf(index));
                                    countdownText.setText(String.valueOf(index));
                                } else if (index == 0) {
//                                    voicePlayerUtil.startVoice("跑步开始");
                                    SpeechUtil.getInstance().speak("跑步开始");
                                    countdownText.setText("Go!");

                                } else {
                                    countdownText.setVisibility(View.GONE);
                                    mService.setState(RunningService.RUNNING);
                                    lock.setVisibility(View.VISIBLE);
                                    stop.setVisibility(View.VISIBLE);
                                    start.setImageResource(R.drawable.ic_finish);
                                    stop.setText("暂停");
                                }
                            }
                        });
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    float disTab = 0;


    /**
     * 上传数据
     */
    public void uploadData() {

        int time = RunningUtils.transformTimeStrToSeconds(sportTime.getText().toString());//本次时间
        final double mDistance = getTotalDistance()/1000;//本次距离
        apiStores.getAddSportRecord(UserBean.getUserBean().userId,
                mDistance,
                time, time, //总时间
                mDistance,  //总距离
                districtDistance / 1000,
                Double.parseDouble(myCalories.getText().toString()), Integer.parseInt(tvSteps.getText().toString()), 0, province, city, area, distract_code, id).enqueue(new Callback<AddSportsBean>() {
            @Override
            public void onResponse(Call<AddSportsBean> call, Response<AddSportsBean> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 0) {
                        doFinish(response.body().getData().getUrl());
                    } else {
                        mService.setState(FINISH);
                        Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT);
                        finish();

                    }
                }
            }

            @Override
            public void onFailure(Call<AddSportsBean> call, Throwable throwable) {
                dismissProgressDialog();
                mService.setState(PAUSE);
            }
        });
    }

    private void doFinish(String url) {
        if (mService != null) mService.setState(FINISH);
//        voicePlayerUtil.startVoice("跑步结束");
        SportRecordShareActivity.openActivity(SportOutDistrictActivity.this, url, disData);
        finish();
    }

    @Override
    public void onGPSStateChanged(boolean isEnabled) {
        if(isEnabled){
//            if(mService!=null && mService.getRunningState() == RunningService.PAUSE ) onClick(tvStop);
        }
        else {
            if(mService!=null && mService.getRunningState() == RunningService.RUNNING ) onClick(stop);
        }
    }

    /**
     * 刷新ui
     *
     * @param data
     */
    @Override
    public void onDataUpdated(Bundle data) {
        if (isFirstUpData) {
            polylineOption2.width(12).color(Color.parseColor("#7a2075"));
            isFirstUpData = false;
        }
        disData = decimalFormat.format(data.getFloat(DISTANCE) / 1000);
        dis.setText(disData);                                                //当前运动近距离
        mySpeed.setText(data.getString(PACE));
        tvSteps.setText(data.getString(STEP));
        myCalories.setText(data.getString(CALORIE));

        if (disTab!=getTotalDistance()) {
            drawLine(getTotalDistance() + disOld);//绘制轨迹
            disTab = getTotalDistance();
        }
        p++;
    }

    @Override
    public void onRunningTime(final int runningTime) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sportTime.setText(RunningUtils.getHmsTime(runningTime));
            }
        });
    }


    int p = 0;

    @Override
    protected void onStart() {
        super.onStart();

        Intent intentServices = new Intent(SportOutDistrictActivity.this, RunningService.class);
        intentServices.putExtra(RunningService.RUNNING_ACTIVITY, this.getClass().getName());
        intentServices.putExtra(RunningService.NEED_SAVE_TRACE, true);
        intentServices.putExtra(RunningService.NEED_EXTRA_DATA, true);
        intentServices.putExtra(RunningService.NEED_SAVE_STATE, true);
        startService(intentServices);
        bindService(intentServices, connection, Context.BIND_AUTO_CREATE);

    }

    /**
     * 获取服务对象
     */
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RunningService.LocalBinder binder = (RunningService.LocalBinder) service;
            mService = binder.getService();
            mService.registerOnDataUpdatedListener(SportOutDistrictActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };


    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mService.hasOngoingRunning() && mService != null) {
                showDialog();
            } else
                finish();


            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("是否保存并上传数据？");
        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mService.setState(FINISH);
                finish();
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                showProgressDialog();
                uploadData();
            }
        });
        builder.show();
    }

    /**
     * 这是兼容的 AlertDialog
     */
    private void showDialog() {

      /*
      这里使用了 android.support.v7.app.AlertDialog.Builder
      可以直接在头部写 import android.support.v7.app.AlertDialog
      那么下面就可以写成 AlertDialog.Builder
      */
        final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("跑步还在进行中，请结束后退出");
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(context, "请先结束运动", Toast.LENGTH_SHORT).show();

            }
        });
        builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }

    @Subscribe
    public void onMessageEvent(boolean flag) {
        if (flag) {
            mService.setState(FINISH);
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mService != null)
            mService.unRegisterOnDataUpdatedListener();
        if (connection != null)
            unbindService(connection);
    }


}
